﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Json2Hsm
{
    internal class Program
    {
       
        static void Main(string[] args)
        {
            try
            {
                string input = string.Empty;
                string output = string.Empty;
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].Equals("-i") && i + 1 < args.Length)
                    {
                        input = args[i + 1];
                    }
                    if (args[i].Equals("-o") && i + 1 < args.Length)
                    {
                        output = args[i + 1];
                    }
                }
                if (input == string.Empty)
                {
                    Console.WriteLine("输入为空 请使用-i 文件地址");
                    return;
                }
                string file = ReadFile(input);
                AllJsonMachines json = JsonConvert.DeserializeObject<AllJsonMachines>(file);
                CreateFile create = new CreateFile(json);
                string hFile = create.outputH();
                string smFile = create.outputSMFile();

                if (Directory.Exists(output))
                {
                    output = output + "/out";
                    if (!Directory.Exists(output))
                    {
                        Directory.CreateDirectory(output);
                    }
                    File.WriteAllText(output + "/sm.h", hFile);
                    File.WriteAllText(output + "/sm.c", smFile);
                    String str = string.Empty;
                    if (File.Exists(output + "/sm_user.c"))
                    {
                        str = File.ReadAllText(output + "/sm_user.c");
                    }

                    str = create.outputSMUserFile(str);
                    File.WriteAllText(output + "/sm_user.c", str);

                }
                else
                {
                    Console.WriteLine("输出地址不存在");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
           
        }

        static string ReadFile(string input)
        {
            if (File.Exists(input))
            {
                using(StreamReader fs = new StreamReader(input))
                {
                    StringBuilder sb = new StringBuilder();
                    string res;
                    while((res = fs.ReadLine()) != null)
                    {
                        sb.Append(res);
                    }
                    return sb.ToString();
                }
                    
            }
            else
            {
                Console.WriteLine("输入文件不存在");
            }
            
            return null;
        }
    }
}
